<?php


namespace App\Entity;


use App\Constants\ErrorCode;

/**
 * @property int $code
 * @property string $message
 * @property object $data
 * @property string $timestamp
 */
class Result extends BaseEntity
{

    // -----------------错误信息返回---------------------------------------//
    const TOKEN_WRONG = 1001; // 密钥无效
    const USER_WRONG = 1002;//用户不存在
    const CALL_API_NUM_EMPTY = 1003;//用户次数已用尽
    const PARAMS_WRONG = 1004;//参数缺失
    const ELEC_VLAUE_WRONG = 1005;//电量值错误

    // -----------------错误信息返回---------------------------------------//

    static $_wrongMessage = array(
        self::TOKEN_WRONG => '密钥过期,请重新获取',
        self::USER_WRONG => '用户不存在',
        self::CALL_API_NUM_EMPTY => '用户次数已用尽',
        self::PARAMS_WRONG => '参数缺失',
        self::ELEC_VLAUE_WRONG=>'电量值错误'
    );


    public function __construct(int $code, string $message, $payload = null)
    {
        parent::__construct([]);
        $this->code = $code;
        $this->message = $message;
        $this->timestamp = time();
        $this->data = $payload;
    }

    public static function respond(int $code, $payload, string $message = null): Result
    {
        if (empty($message)) {
            $message = ErrorCode::getMessage($code) ?? '服务器走丢啦，请稍后再试';
        }

        return new Result($code, $message, $payload);
    }

    public static function success($payload = [], string $message = null): Result
    {
        return self::respond(ErrorCode::SUCCESS, $payload, $message);
    }

    public static function error(int $code, string $message = null, $payload = null): Result
    {
        return self::respond($code, $payload, self::$_wrongMessage[$code]?? $message);
    }
}
